package org.example.demo.controller;

import cn.hutool.core.util.IdUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.example.demo.entity.dto.Result;
import org.example.demo.service.DatasourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/datasource")
@Api(tags = "数据源")
@Slf4j
public class DatasourceController {

    @Autowired
    private DatasourceService datasourceService;

    private Map<String, Connection> datasourceServiceMap = new HashMap<>();

    @GetMapping("/create/{type}")
    @ResponseBody
    @ApiOperation(value = "创建数据源")
    public Result<String> createDatasource(@PathVariable("type") String datasourceType) throws Exception {
//        Connection connection = null;
//        switch (datasourceType) {
//            case "mysql":
//                connection = DriverManager.getConnection(url, username, password);
//                break;
//            default:
//                throw new RuntimeException("不支持的数据库");
//        }
        String datasourceName = IdUtil.simpleUUID();
//        datasourceServiceMap.put(datasourceName, connection);
        return Result.ok(datasourceName);
    }

    @GetMapping("/{name}/tables")
    @ResponseBody
    @ApiOperation(value = "数据表")
    public Result<List> getTables(@PathVariable("name") String datasourceName) {
        Connection connection = datasourceServiceMap.get(datasourceName);
        if (connection != null) {
            List tables = datasourceService.getTables(connection);
            return Result.ok(tables);
        }
        return Result.error("无效的数据源");
    }

    @GetMapping("/{name}/{table}/columns")
    @ResponseBody
    @ApiOperation(value = "数据列")
    public Result<List> getColumns(@PathVariable("name") String datasourceName,
                                   @PathVariable("table") String tableName) {
        Connection connection = datasourceServiceMap.get(datasourceName);
        if (connection != null) {
            List columns = datasourceService.getColumns(connection, tableName);
            return Result.ok(columns);
        }

        return Result.error("无效的数据源");
    }
}
